package test.arch.chameleon.module.mail;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import javax.mail.Message;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mail.SimpleMailMessage;

import test.module.AbstractTimerTestSupport;
import arch.chameleon.module.mail.MailEngine;
import arch.chameleon.module.mail.impl.DefaultMailEngine;

import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;

/**
 * 邮件测试
 * @author George
 * （以GreenMail作为测试邮件服务器）
 */
public class MailTestcase extends AbstractTimerTestSupport {

	private GreenMail greenMail;

	@Override
	@Before
	public void setUp() {
		super.setUp();
		greenMail = new GreenMail(ServerSetup.SMTP);
		greenMail.setUser("admin@greenmail.com", "password");
		greenMail.start();
		log.info("green mail server started...");
	}
	
	@Test
	public void sendAndReceive(){
		try{
			MailEngine objMailEngine = this.applicationContext.getBean(DefaultMailEngine.class);
			//设置邮件发送参数
			SimpleMailMessage objMsg = new SimpleMailMessage();
			objMsg.setSubject("测试主题");
			objMsg.setText("<h3>测试内容</h3>");
			objMsg.setTo("user@greenmail.com");
			boolean bSent = objMailEngine.sendHtmlMail(objMsg);
			log.info("mail sent: {}", new Object[]{bSent});
			
			greenMail.waitForIncomingEmail(2000, 1);
			
			Message[] aryObjMsg = greenMail.getReceivedMessages();
			assertEquals(1, aryObjMsg.length);
			log.info("\nFrom: {}\nContent:{}\nSubject:{}\n ", new Object[]{
					aryObjMsg[0].getFrom()[0],
					aryObjMsg[0].getContent(),
					aryObjMsg[0].getSubject()
			});
		}catch(Throwable t){
			log.error(t.getMessage(), t);
			fail();
		}	
	}
	

	@Override
	@After
	public void tearDown() {
		super.tearDown();
		greenMail.stop();
	}
	
	
}
